﻿using DHQGHN.Common;
using DHQGHN.DAL.BO.DHQG;
using DHQGHN.DAL.Common;
using DHQGHN.PM2.Models;
using DHQGHN.PM2.Models.DHQG;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace DHQGHN.PM2.Controllers
{
    public class NguoiDungChiTieuController : BaseController
    {
        //
        // GET: /NguoiDungChiTieu/
        NguoiDungBO _sqlNguoiDungBO;
        NguoiDungChiTieuBO _sqlNguoiDungChiTieuBO;
        public ActionResult Index(NguoiDungChiTieuModel a = null, int pageIndex = 0, string sort = "Id", string sortDir = "ASC", string curentID = "")
        {
            ViewBag.ActiveMenus = ViewBag.ActiveMenus == null ? new System.Collections.Hashtable() : ViewBag.ActiveMenus;

            string strInputMenuUrl = "/NguoiDungChiTieu/Index";
            List<DHQGHN.PM2.Models.MenuModel> listMenu = Session["MenuList"] as List<DHQGHN.PM2.Models.MenuModel>;
            if (listMenu.Count > 0)
            {
                for (int i = 0; i < listMenu.Count; i++)
                {
                    if (listMenu[i].MenuUrl.ToUpper().Equals(strInputMenuUrl.ToUpper()))
                    {
                        ViewBag.ActiveMenus[listMenu[i].ParentMenuId] = "active";
                        ViewBag.ActiveMenus[listMenu[i].MenuId] = "active";
                        ViewBag.CurrentMenuName = listMenu[i].MenuName;
                        ViewBag.Title = listMenu[i].MenuName;
                    }
                }
            }
            int donViId = GetDonViId();
            ViewBag.LaDonVi = donViId > 0 ? true : false;
            ViewBag.DanhSachNguoiDung = GetDanhSachUser();
            ViewBag.DanhSachDonVi = GetDonVi();
            ViewBag.DanhSachNamKH = GetListNamKeHoachId();
            if (a == null)
            {
                a = new NguoiDungChiTieuModel();
            }

            var model = search(a, pageIndex, 0);
            return View(model);
        }

        [HttpPost]
        public ActionResult CreatePopupUpdate(NguoiDungChiTieuModel model)
        {
            try
            {
                DAL.Models.DHQG.NguoiDungChiTieu DALModel = new DAL.Models.DHQG.NguoiDungChiTieu();
                DALModel.NAM_KE_HOACH_ID = model.NAM_KE_HOACH_ID;
                DALModel.NGUOI_DUNG_ID = model.NGUOI_DUNG_ID;
                DALModel.DON_VI_ID = model.DON_VI_ID;
                _sqlNguoiDungChiTieuBO = new NguoiDungChiTieuBO();
                List<DAL.Models.DHQG.NguoiDungChiTieu> listChiTieu = _sqlNguoiDungChiTieuBO.GetListChiTieu(DALModel);
                List<NguoiDungChiTieuModel> nguoiDungChiTieuModel = new List<NguoiDungChiTieuModel>();
                for (int i = 0; i < listChiTieu.Count; i++)
                {
                    nguoiDungChiTieuModel.Add(new NguoiDungChiTieuModel(listChiTieu[i]));
                }
              
                ViewBag.NguoiDung = new List<SelectListItem>() { new SelectListItem() { Value = model.NGUOI_DUNG_ID.ToString(), Text = model.TAI_KHOAN } };
                ViewBag.NamKeHoach = new List<SelectListItem>() { new SelectListItem() { Value = model.NAM_KE_HOACH_ID.ToString(), Text = model.NAM_KE_HOACH.ToString() } };
                ViewBag.DonVi = new List<SelectListItem>() { new SelectListItem() { Value = model.DON_VI_ID.ToString(), Text = model.TEN_DON_VI } };
                //ViewBag.DanhSachChiTieu = nguoiDungChiTieuModel;

                return View(nguoiDungChiTieuModel);
            }
            catch
            {
                throw;
            }
        }

        [HttpPost]
        public ActionResult ActionSearch(NguoiDungChiTieuModel aModel = null, int pageIndex = 0, string sort = "UserInRoleId", string sortDir = "ASC", int currentId = -1)
        {
            try
            {
                if (aModel == null)
                {
                    aModel = new NguoiDungChiTieuModel();
                }

                var model = search(aModel, pageIndex, currentId);
                return PartialView("~/Views/NguoiDungChiTieu/_NguoiDungChiTieuList.cshtml", model);
            }
            catch (Exception ex)
            {
                //logger.Error(ex.ToString());
                throw;
            }
        }

        [HttpPost]
        [ValidateInput(false)]
        [AjaxValidateAntiForgeryToken]
        public ActionResult ActionSave(NguoiDungChiTieuModel model, int[] maCap1)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    List<DAL.Models.DHQG.NguoiDungChiTieu> data = new List<DAL.Models.DHQG.NguoiDungChiTieu>();
                    for (int i = 0; i < maCap1.Length; i++)
                    {
                        data.Add(new DAL.Models.DHQG.NguoiDungChiTieu()
                        {
                            DON_VI_ID = model.DON_VI_ID,
                            NAM_KE_HOACH_ID = model.NAM_KE_HOACH_ID,
                            NGUOI_DUNG_ID = model.NGUOI_DUNG_ID,
                            MA_CAP1 = maCap1[i].ToString(),
                            CHI_TIEU_ID = 0
                        });
                    }
                    _sqlNguoiDungChiTieuBO = new NguoiDungChiTieuBO();
                    bool result = _sqlNguoiDungChiTieuBO.Save(data);
                    if (result)
                    {
                        return Json(JsonResponse.Json200("Gán chỉ tiêu cho người dùng thành công!"));
                    }
                    else
                    {
                        return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));

                    }
                }
            }
            catch (Exception ex)
            {
                //logger.Error(ex.ToString());
                throw;
            }
            return null;
        }

        [AjaxValidateAntiForgeryToken]
        [HttpPost]
        public ActionResult ActionDelete(int[] ids)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    _sqlNguoiDungChiTieuBO = new NguoiDungChiTieuBO();
                    bool result = _sqlNguoiDungChiTieuBO.Delete(ids);
                    if (result)
                    {
                        return Json(JsonResponse.Json200("Xóa chỉ tiêu thành công!"));
                    }
                    else
                    {
                        return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));
                    }                    
                }
            }
            catch (Exception ex)
            {
                //logger.Error(ex.ToString());
                throw;
            }
            return null;
        }

        [HttpPost]
        public JsonResult GetUserByDonVi(int donViId)
        {
            try
            {
                NguoiDungBO nguoiDungBO = new NguoiDungBO();
                List<DAL.Models.DHQG.NguoiDung> danhSachNguoiDung = nguoiDungBO.GetListUserByDonViId(donViId);
                List<SelectListItem> items = new List<SelectListItem>();
                if (danhSachNguoiDung == null)
                {
                    return Json(items, JsonRequestBehavior.AllowGet);
                }
                int len = danhSachNguoiDung.Count;
                for (int i = 0; i < len; i++)
                {
                    items.Add(new SelectListItem() { 
                        Value = danhSachNguoiDung[i].NGUOI_DUNG_ID.ToString(),
                        Text = string.IsNullOrEmpty(danhSachNguoiDung[i].HO_VA_TEN) ? danhSachNguoiDung[i].TAI_KHOAN :
                                        danhSachNguoiDung[i].TAI_KHOAN + "(" + danhSachNguoiDung[i].HO_VA_TEN + ")"
                    });
                }
                return Json(items, JsonRequestBehavior.AllowGet);
            }
            catch 
            {                
                throw;
            }
        }

        [HttpPost]
        public JsonResult UpdateQuyenChot(int nguoiDungId, int isFix)
        {
            try
            {
                _sqlNguoiDungBO = new NguoiDungBO();
                bool result = _sqlNguoiDungBO.UpdateQuyenChot(nguoiDungId, isFix);
                
                return Json(new { Success = result });
            }
            catch
            {                
                throw;
            }
        }

        private DataPage<NguoiDungChiTieuModel> search(NguoiDungChiTieuModel myModel, int pageIndex, int currentId)
        {
            try
            {
                _sqlNguoiDungChiTieuBO = new NguoiDungChiTieuBO();
                DataPage<NguoiDungChiTieuModel> models = new DataPage<NguoiDungChiTieuModel>();
                DataPage<DAL.Models.DHQG.NguoiDungChiTieu> DALModel = _sqlNguoiDungChiTieuBO.GetListPaging(myModel.ToDALModel(), pageIndex, PageSize);
                var lstItem = DALModel.Data;
                foreach (DAL.Models.DHQG.NguoiDungChiTieu m in lstItem)
                {
                    models.Data.Add(new NguoiDungChiTieuModel(m));
                }

                //GroupInRoleModel model = null;
                if (currentId >= 0 && models.Data.Count > 0)
                {
                    //model = models.Data.Find(groupInRole => groupInRole.GroupInRoleID == currentId);
                    //models.CustomData = model;
                }
                else
                {
                    models.CustomData = myModel;
                }
                if (models.Data.Count > 0)
                {
                    //Tao component phan trang
                    var pagNative = new Pagination
                    {
                        ActionName = "actionSearch",
                        ModelName = "GroupInRole",
                        CurrentPage = pageIndex,
                        InputSearchId = string.Empty,
                        TagetReLoadId = "group-in-role-list",

                    };
                    pagNative.TotalRows = models.Data[0].RECORD_COUNT;
                    pagNative.CurrentRow = models.Data.Count;
                    ViewBag.Pagination = pagNative;
                }

                _sqlNguoiDungBO = new NguoiDungBO();
                DAL.Models.DHQG.NguoiDung nguoiDung = _sqlNguoiDungBO.GetById(myModel.NGUOI_DUNG_ID);
                if (nguoiDung != null)
                {
                    if (nguoiDung.IS_FIX < 0 && nguoiDung.IS_FIX > 1)
                    {
                        nguoiDung.IS_FIX = 0;
                    }
                    ViewBag.IS_FIX = nguoiDung.IS_FIX == 1 ? true : false;
                }
                else ViewBag.IS_FIX = 0;
                

                return models;
            }
            catch (Exception ex)
            {
                //logger.Error(ex.ToString());
                throw;
            }
        }

        private List<SelectListItem> GetDanhSachUser()
        {
            int donViId = GetDonViId();
            _sqlNguoiDungBO = new NguoiDungBO();
            List<DAL.Models.DHQG.NguoiDung> danhSachNguoiDung = new List<DAL.Models.DHQG.NguoiDung>();
            if (donViId > 0) //la don vi
            {
                danhSachNguoiDung = _sqlNguoiDungBO.GetListUserByDonViId(donViId);
            }
            
            List<SelectListItem> items = new List<SelectListItem>() { 
                new SelectListItem(){
                    Value = "-1",
                    Text = "--- Chọn tài khoản ---"
                }
            };
            for (int i = 0; i < danhSachNguoiDung.Count; i++)
            {
                items.Add(new SelectListItem()
                {
                    Value = danhSachNguoiDung[i].NGUOI_DUNG_ID.ToString(),
                    Text = danhSachNguoiDung[i].TAI_KHOAN
                });
            }

            return items;
        }

        private List<SelectListItem> GetDonVi()
        {
            NguoiDungModel nguoiDungInfo = Session["NguoiDungInfo"] as NguoiDungModel;
            DonViBO donViBO = new DonViBO();
            List<DAL.Models.DHQG.DonVi> danhSachDonVi = new List<DAL.Models.DHQG.DonVi>();
            List<SelectListItem> items = new List<SelectListItem>();
            bool selected = false;
            if (nguoiDungInfo.listDonVi != null && nguoiDungInfo.listDonVi.Count > 0)
            {
                 DAL.Models.DHQG.DonVi donVi = donViBO.GetById(nguoiDungInfo.listDonVi[0].DonViId);
                 danhSachDonVi.Add(donVi);
                 selected = true;
            }
            else
            {
                danhSachDonVi = donViBO.GetAll();
                items.Add(new SelectListItem()
                {
                    Value = "-1",
                    Text = "--- Chọn đơn vị ---"
                });
            }
            
            for (int i = 0; i < danhSachDonVi.Count; i++)
            {
                items.Add(new SelectListItem()
                {
                    Value = danhSachDonVi[i].DonViId.ToString(),
                    Text = danhSachDonVi[i].TenDonVi,
                    Selected = selected
                });
            }

            return items;
        }
        
        private List<SelectListItem> GetListNamKeHoachId()
        {
            NamKeHoachBO namKHBO = new NamKeHoachBO();
            List<DAL.Models.DHQG.NamKeHoach> danhSachNKH = namKHBO.GetAllNamkehoach();
            List<SelectListItem> items = new List<SelectListItem>();
            for (int i = 0; i < danhSachNKH.Count; i++)
            {
                items.Add(new SelectListItem()
                {
                    Value = danhSachNKH[i].NAM_KE_HOACH_ID.ToString(),
                    Text = danhSachNKH[i].NAM_KE_HOACH.ToString()

                });
            }

            return items;
        }

        private int GetDonViId()
        {
            int donViId = 0;
            if (Session["NguoiDungInfo"] != null)
            {
                NguoiDungModel userInfo = (NguoiDungModel)Session["NguoiDungInfo"];
                List<DHQGHN.PM2.Models.DonViModel> listDonVi = userInfo.listDonVi;
                if (listDonVi != null)
                {
                    donViId = listDonVi.Count > 0 ? listDonVi[0].DonViId : 0;
                }
            }

            return donViId;
        }
    }
}